<!--此组件必须选到具体的区县-->
<template>
  <el-cascader
    v-model="selectedOptions"
    :options="options"
    :props="cascaderProps"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :size="size"
    :show-all-levels="showAllLevels"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
import { regionData, provinceAndCityData, codeToText } from 'element-china-area-data'

export default {
  name: 'RegionPicker',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择省市区'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: '',
      validator: (value) => ['', 'medium', 'small', 'mini'].includes(value)
    },
    showAllLevels: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      selectedOptions: [],
      options: regionData,
      cascaderProps: {
        value: 'value',
        label: 'label',
        children: 'children'
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.selectedOptions = newVal
      }
    }
  },
  methods: {
    handleChange(value) {
      // 触发input事件实现v-model
      this.$emit('input', value)
      
      // 构建完整的地区信息对象
      const regionInfo = this.buildRegionInfo(value)
      
      // 触发change事件，传递完整的地区信息
      this.$emit('change', regionInfo)
    },
    buildRegionInfo(codes) {
      if (!codes || codes.length !== 3) {
        return {
          provinceCode: "",
          provinceName: "",
          cityCode: "",
          cityName: "",
          districtCode: "",
          districtName: ""
        }
      }
      
      const [provinceCode, cityCode, districtCode] = codes
      
      return {
        provinceCode: provinceCode,
        provinceName: codeToText[provinceCode] || "",
        cityCode: cityCode,
        cityName: codeToText[cityCode] || "",
        districtCode: districtCode,
        districtName: codeToText[districtCode] || ""
      }
    }
  }
}
</script>